<!--查看流程图的公用组件-->

<template>
  <div class="audit-img">
    <img :src="processImg" class="img-area" ref="processImg">
    <!--  processImg2不显示，用来模拟图片占用高度和宽度，通过onload方法对图片进行裁剪，赋值给processImg，若是仍赋值processImg2，会造成无限onload  -->
    <img :src="processImg2" class="img-area" style="display: none" ref="processImg2">
  </div>

</template>

<script>
import {getAuditedImg} from "../../api/bpmn-api";

export default {
  name: "audit-img",
  props:{
    processObject:{
      type:Object,
      default(){
        return {
          processInstanceId:"",
          processDefinitionId:"",
        }
      }
    }
  },
  data(){
    return{
      processImg:"",
      processImg2:"",
    }
  },
  created() {
    this.getAuditImg()
  },
  methods:{
    //获取流程图
    getAuditImg() {
      getAuditedImg({
          processInstanceId: this.processObject.processInstanceId,
          processDefinitionId: this.processObject.processDefinitionId,
        }
      ).then(res => {
        if (res.status === 200) {
          const that = this
          that.processImg2 = window.URL.createObjectURL(res.data)
          let img =  that.$refs.processImg2
          img.onload = function(){
            let c = document.createElement('canvas');//创建处理画布对象
            let ctx = c.getContext('2d');
            c.width = img.width;
            c.height = img.height;
            ctx.drawImage(img,0,0);//绘制
            let imgData = ctx.getImageData(0, 0, c.width, c.height).data;//读取图片数据
            let lOffset = c.width, rOffset = 0,tOffset = c.height, bOffset = 0;
            for (let i = 0; i < c.width; i++) {
              for (let j = 0; j < c.height; j++) {
                let pos = (i + c.width * j) * 4
                if (imgData[pos] == 255 || imgData[pos + 1] == 255 || imgData[pos + 2] == 255 || imgData[pos + 3] == 255) {
                  bOffset = Math.max(j, bOffset); // 找到有色彩的最下端
                  rOffset = Math.max(i, rOffset); // 找到有色彩的最右端
                  tOffset = Math.min(j, tOffset); // 找到有色彩的最上端
                  lOffset = Math.min(i, lOffset); // 找到有色彩的最左端
                }
              }
            }
            lOffset++;
            rOffset++;
            tOffset++;
            bOffset++;
            let x = document.createElement("canvas");//创建处理后画布对象
            x.width = rOffset-250;
            x.height = bOffset+100;
            let xx = x.getContext("2d");
            xx.drawImage(img, lOffset-100, tOffset-150, x.width, x.height, 0, 0, x.width, x.height);//绘制
            that.$refs.processImg.src = x.toDataURL()
          }
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
.audit-img{
  .img-area{
    max-height: 480px;
    margin-top: -100px;
    margin-left: 10px;
  }
}
</style>
